package com.aaa.controller;

import cn.hutool.core.util.ObjectUtil;
import com.aaa.service.UserService;
import com.aaa.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import  java.util.Map;

/**
 * @author ：Teacher陈
 * @date ：Created in 2020/10/26 16:45
 * @description：登录servlet
 * @modified By：
 * @version: 1.0
 */
@WebServlet(name = "LoginServlet" ,urlPatterns = "/userLogin")
public class LoginServlet   extends HttpServlet {
    UserService userService= new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //返回所有的请求参数
        Map<String, String[]> parameterMap = req.getParameterMap();
        //将 Map<String, String[]>转换成 Map<String, String>
        Map<String, String> myMap = new HashMap<>();
        //遍历原始map
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            if (ObjectUtil.isNotEmpty(entry.getValue())) {
                myMap.put(entry.getKey(), entry.getValue()[0]);
            }
        }
        String method = myMap.get("method") + "";
       //登录业务
        //判断用户名和密码是否正确
        List<Map<String, Object>> allUser = userService.findAllUser(myMap);
        if(allUser!=null&&allUser.size()>0){
            //如果用户名密码合法，将用户所对应的权限菜单放在session中
            HttpSession session = req.getSession();
            //根据用户登录名获取所对应的权限
            Map<String, Object> menuMap = userService.findAllMenuByLoginName(myMap.get("username"));
            session.setAttribute("firstMenus",menuMap.get("firstMenus"));
            session.setAttribute("secondMenus",menuMap.get("secondMenus"));
            session.setAttribute("user",allUser.get(0));
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }


    }
}
